package middleware

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

type AccessLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w AccessLogWriter) Write(p []byte) (int, error) {
	if n, err := w.body.Write(p); err != nil {
		return n, err
	}

	return w.ResponseWriter.Write(p)
}

func AccessLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		bodyWriter := &AccessLogWriter{
			ResponseWriter: c.Writer,
			body:           bytes.NewBufferString(""),
		}
		c.Writer = bodyWriter
		remoteIP := c.Request.Host
		statusCode := c.Writer.Status()
		beginTime := time.Now().Unix()
		c.Next()
		endTime := time.Now().Unix()
		fmt.Printf("remoteIP:= %s,statusCode:= %d,beginTime:= %d ,endTime:= %d \n", remoteIP, statusCode, beginTime, endTime)
	}
}
